package com.heima.user.service.Impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticelFeifn;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.article.pojos.ApUser;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Autowired
    ApUserMapper apUserMapper;

    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ArticelFeifn articleFeign;



    @Override
    public ResponseResult PageRealnameQuery(AuthDTO dto) {
        //判断dto前端参数是否为空
        if (dto == null){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"无效参数");
        }
        dto.checkParam();

        Integer page = dto.getPage();
        Integer size = dto.getSize();
        Page<ApUserRealname> page1 = new Page<>(page,size);
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.<ApUserRealname>lambdaQuery();
        if (dto.getStatus() != null){
           wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }

        IPage<ApUserRealname> resultPage = this.page(page1, wrapper);

        return new PageResponseResult(dto.getPage(), dto.getSize(),
                resultPage.getTotal(), resultPage.getRecords());

    }





//分布式事务
    @GlobalTransactional(timeoutMills = 100000,rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {

        if (dto.getId()==null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUserRealname apUserRealname = getOne(Wrappers.<ApUserRealname>lambdaQuery()
                .eq(ApUserRealname::getId,dto.getId())
        );
        if (apUserRealname == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        if (!AdminConstants.WAIT_AUTH.equals(apUserRealname.getStatus())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }

        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if (apUser == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        apUserRealname.setStatus(status);

        if (StringUtils.isNotBlank(dto.getMsg())){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);


        //9
        if (AdminConstants.PASS_AUTH.equals(status)){
            //开通自媒体账户
            WmUser wmUser = creatWmuser(apUser);
            //开通作者
            createAuthor(apUser,wmUser);
        }
        return ResponseResult.okResult();
    }




        //创建作者
    private void createAuthor(ApUser apUser, WmUser wmUser) {
        ResponseResult<ApAuthor> result = articleFeign.findByUserId(apUser.getId());
        if (result.getCode().intValue() != 0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"创建自媒体出错");
        }
        ApAuthor apAuthor = result.getData();


        if (apAuthor != null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }

        apAuthor = new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(2);
        apAuthor.setUserId(apUser.getId());
        apAuthor.setCreatedTime(new Date());
        apAuthor.setWmUserId(wmUser.getId());


        ResponseResult result1 = articleFeign.save(apAuthor);

        if (result1.getCode().intValue() != 0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"创建自媒体出错");
        }

    }







    private WmUser creatWmuser(ApUser apUser) {

        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if (result.getCode().intValue() != 0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"创建作者出错");
        }
        WmUser vmuser = result.getData();

        if (vmuser != null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }

        vmuser = new WmUser();
        vmuser.setApUserId(apUser.getId());
        vmuser.setName(apUser.getName());
        vmuser.setPassword(apUser.getPassword());
        vmuser.setSalt(apUser.getSalt());
        vmuser.setNickname(apUser.getName());
        vmuser.setImage(apUser.getImage());
        vmuser.setPhone(apUser.getPhone());
        vmuser.setStatus(9);
        vmuser.setType(0);
        vmuser.setCreatedTime(new Date());


        ResponseResult<WmUser> responseResult = wemediaFeign.save(vmuser);

        if (responseResult.getCode().intValue() != 0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"创建作者出错");
        }
        return responseResult.getData();
    }



}
